from pathlib import Path
import platform
import subprocess
from typing import Dict, Optional
from .base import BaseTTSEngine


class MacOSSayTTSEngine(BaseTTSEngine):
    """
    macOS内置say命令TTS引擎实现
    """
    
    def __init__(self, config: Optional[Dict] = None):
        super().__init__(config)
        self.is_macos = platform.system() == "Darwin"
        self.initialize()
    
    def initialize(self) -> bool:
        """
        初始化macOS say引擎
        """
        if not self.is_macos:
            print("✗ macOS say引擎初始化失败: 非macOS系统")
            return False
        
        # 检查say命令是否可用
        try:
            subprocess.run(["which", "say"], check=True, capture_output=True, text=True)
            self.initialized = True
            print("✓ macOS say引擎初始化成功")
            return True
        except Exception as e:
            print(f"✗ macOS say引擎初始化失败: {e}")
            return False
    
    def synthesize(self, text: str, output_path: Path, lang: str = "en") -> bool:
        """
        使用macOS内置的say命令进行语音合成
        """
        if not self.is_available():
            print(f"  ⚠ macOS say引擎不可用，无法合成文本: {text}")
            return False
        
        try:
            # 为不同语言设置合适的语音
            voice_map = {
                'en': 'Karen',  # 默认英语语音
                'zh': 'Tingting',  # 中文语音
            }
            voice = voice_map.get(lang, 'Alex')  # 默认语音
            
            # 使用say命令生成音频文件
            cmd = ["say", "-v", voice, "-o", str(output_path), text]
            subprocess.run(cmd, check=True, capture_output=True, text=True)
            
            print(f"  ✓ 生成音节语音: {text} -> {output_path.name} (macOS say)")
            return True
        except Exception as e:
            print(f"  ⚠ macOS say命令失败: {e}")
            return False
    
    def is_available(self) -> bool:
        """
        检查macOS say引擎是否可用
        """
        return self.is_macos and self.initialized
    
    def get_name(self) -> str:
        """
        获取引擎名称
        """
        return "macos-say"